package site.xuxingcan.ninecut;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import site.xuxingcan.ninecut.Adapter.HorizontalListViewAdapter;
import site.xuxingcan.ninecut.Util.BitmapUtil;
import site.xuxingcan.ninecut.View.HorizontalListView;
import site.xuxingcan.ninecut.View.MySignaturePad;
import uk.co.senab.photoview.PhotoViewAttacher;

public class MainActivity extends Activity {

    private PhotoViewAttacher mAttacher;
    private int screenWidth, screenHeight;
    private ImageView mImageView;
    private boolean isEnableDraw = false;
    private MySignaturePad mSignaturePad;
    private HorizontalListView mHorizontalListView;
    private ArrayList<Integer> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WindowManager wm = this.getWindowManager();
        screenWidth = wm.getDefaultDisplay().getWidth();
        screenHeight = wm.getDefaultDisplay().getHeight();

        ViewGroup.LayoutParams lp = findViewById(R.id.content).getLayoutParams();
        lp.height = screenWidth;
        lp.width = screenWidth;
        findViewById(R.id.content).setLayoutParams(lp);

        mSignaturePad = (MySignaturePad) findViewById(R.id.signature_pad);
        mSignaturePad.setIsEnableTouch(isEnableDraw);
        mSignaturePad.setMinWidth(10);
        mSignaturePad.setMaxWidth(10);

        mImageView = (ImageView) findViewById(R.id.image);
        mImageView.setImageResource(R.drawable.test);
        mAttacher = new PhotoViewAttacher(mImageView);
        mAttacher.update();

        list = new ArrayList<>();
        list.add(R.drawable.mask_default_circle);
        list.add(R.drawable.mask_default_constellation);
        list.add(R.drawable.mask_default_flower);
        list.add(R.drawable.mask_default_heart);
        list.add(R.drawable.mask_default_heartall);
        list.add(R.drawable.mask_default_number9);
        list.add(R.drawable.mask_default_reach);
        list.add(R.drawable.mask_default_sharprec);
        list.add(R.drawable.mask_horse_circle);
        list.add(R.drawable.mask_horse_horse);
        list.add(R.drawable.mask_horse_lantern);
        list.add(R.drawable.mask_horse_pane);
        list.add(R.drawable.mask_horse_rectangle);
        list.add(R.drawable.mask_horse_totoro);
        list.add(R.drawable.mask_lei_cat);
        list.add(R.drawable.mask_lei_cell);
        list.add(R.drawable.mask_lei_cupid);
        list.add(R.drawable.mask_lei_dots);
        list.add(R.drawable.mask_lei_glass);
        list.add(R.drawable.mask_lei_hot);
        list.add(R.drawable.mask_lei_ray);
        list.add(R.drawable.mask_lei_storm);
        list.add(R.drawable.mask_shake_dialog);
        list.add(R.drawable.mask_shake_midas);
        list.add(R.drawable.mask_shake_play);
        mHorizontalListView = (HorizontalListView) findViewById(R.id.horizontal_lit_view);
        mHorizontalListView.setAdapter(new HorizontalListViewAdapter(this, list));
        mHorizontalListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ((ImageView) findViewById(R.id.cover)).setImageResource(list.get(position));
            }
        });
        findViewById(R.id.open).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPhotoPath();
            }
        });
        findViewById(R.id.which_one).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isEnableDraw = !isEnableDraw;
                mSignaturePad.setIsEnableTouch(isEnableDraw);
                ((Button) findViewById(R.id.which_one)).setText(isEnableDraw ? "画图" : "拖拽");
            }
        });
        findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
            }
        });
//        File root = new File(Environment.getExternalStorageDirectory(), "9Cut");
//        File[] files = root.listFiles();
//        ArrayList<File> newfiles = new ArrayList<>();
//        for (int i = files.length - 1; i >= 0; i--) {
//            newfiles.add(files[i]);
//        }
//        initShareIntent("com.qzone", newfiles);
    }

    private void save() {
        Bitmap m = convertViewToBitmap(getWindow().getDecorView());
        if (m != null) {
            isEnableDraw = true;
        }
    }

    public static Bitmap convertViewToBitmap(View view) {
        if (view == null) {
            return null;
        }
        int bitmapWidth = view.getWidth();
        int bitmapHeight = view.getHeight();
        try {
            if (bitmapWidth == 0 || bitmapHeight == 0) {
                view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            } else {
                view.measure(View.MeasureSpec.makeMeasureSpec(bitmapWidth, View.MeasureSpec.EXACTLY),
                        View.MeasureSpec.makeMeasureSpec(bitmapHeight, View.MeasureSpec.EXACTLY));
            }
        } catch (Exception e) {
            return null;
        }
        bitmapWidth = view.getMeasuredWidth();
        bitmapHeight = view.getMeasuredHeight();
        view.layout(0, 0, bitmapWidth, bitmapHeight);
        try {
            Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
            view.draw(new Canvas(bitmap));
            return bitmap;
        } catch (OutOfMemoryError ex) {
            return null;
        }
    }

    private void getPhotoPath() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 0) {
            try {
                Uri originalUri = data.getData();
                ContentResolver cr = this.getContentResolver();
                Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(originalUri));
                if (bitmap != null && mImageView != null) {
                    Bitmap mBitmap = BitmapUtil.getBitmapWithLowMemory(bitmap, screenWidth / 2, screenHeight / 2);
                    if (mBitmap == null) {
                        return;
                    }
                    mImageView.setImageBitmap(mBitmap);
                    mAttacher.setScale(2, true);
                    mAttacher.update();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } catch (OutOfMemoryError error) {

            }
        }
    }

    private void initShareIntent(String _package, ArrayList<File> files) {
        boolean found = false;
        Intent share = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
        share.setType("image/*");
        List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(share, 0);
        if (!resInfo.isEmpty()) {
            for (ResolveInfo info : resInfo) {
                if (info.activityInfo.packageName.toLowerCase().contains(_package) ||
                        info.activityInfo.name.toLowerCase().contains(_package)) {
                    ArrayList<Uri> imageUris = new ArrayList<Uri>();
                    for (File f : files) {
                        imageUris.add(Uri.fromFile(f));
                    }
                    share.putExtra(Intent.EXTRA_STREAM, imageUris);
                    share.setPackage(info.activityInfo.packageName);
                    found = true;
                    break;
                }
            }
            if (found) {
                startActivity(Intent.createChooser(share, "Select"));
            } else {
                Toast.makeText(this, "没有找到该应用", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
